# Matrix.Configuration 数据库部署脚本
# 用于PostgreSQL数据库的初始化和迁移

param(
    [Parameter(Mandatory=$false)]
    [string]$ConnectionString = "Host=localhost;Database=MatrixConfiguration;Username=postgres;Password=123456",

    [Parameter(Mandatory=$false)]
    [switch]$DropExisting,

    [Parameter(Mandatory=$false)]
    [switch]$SeedData
)

Write-Host "Matrix.Configuration 数据库部署脚本" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

# 检查PostgreSQL是否可用
function Test-PostgresConnection {
    try {
        $connection = New-Object System.Data.Npgsql.NpgsqlConnection($ConnectionString)
        $connection.Open()
        $connection.Close()
        return $true
    }
    catch {
        Write-Warning "无法连接到PostgreSQL数据库: $($_.Exception.Message)"
        return $false
    }
}

# 删除现有数据库（如果指定）
function Remove-ExistingDatabase {
    if ($DropExisting) {
        Write-Host "正在删除现有数据库..." -ForegroundColor Yellow

        # 从连接字符串中提取数据库信息
        $builder = New-Object System.Data.Common.DbConnectionStringBuilder
        $builder.set_ConnectionString($ConnectionString)
        $host = $builder["Host"]
        $username = $builder["Username"]
        $password = $builder["Password"]
        $database = $builder["Database"]

        # 连接到postgres数据库删除目标数据库
        $adminConnectionString = "Host=$host;Database=postgres;Username=$username;Password=$password"

        try {
            $connection = New-Object System.Data.Npgsql.NpgsqlConnection($adminConnectionString)
            $connection.Open()

            $command = $connection.CreateCommand()
            $command.CommandText = "DROP DATABASE IF EXISTS `"$database`";"
            $command.ExecuteNonQuery()

            $command.CommandText = "CREATE DATABASE `"$database`";"
            $command.ExecuteNonQuery()

            $connection.Close()
            Write-Host "数据库重新创建完成" -ForegroundColor Green
        }
        catch {
            Write-Error "删除/创建数据库失败: $($_.Exception.Message)"
            exit 1
        }
    }
}

# 应用数据库迁移
function Invoke-DatabaseMigration {
    Write-Host "正在应用数据库迁移..." -ForegroundColor Yellow

    try {
        Set-Location $PSScriptRoot\..
        & dotnet ef database update --project . --connection $ConnectionString

        if ($LASTEXITCODE -eq 0) {
            Write-Host "数据库迁移应用成功" -ForegroundColor Green
        } else {
            Write-Error "数据库迁移失败"
            exit 1
        }
    }
    catch {
        Write-Error "应用迁移时发生错误: $($_.Exception.Message)"
        exit 1
    }
}

# 插入种子数据
function Invoke-SeedData {
    if ($SeedData) {
        Write-Host "正在插入种子数据..." -ForegroundColor Yellow

        # 这里可以添加种子数据逻辑
        Write-Host "种子数据插入完成" -ForegroundColor Green
    }
}

# 主执行逻辑
if (-not (Test-PostgresConnection)) {
    Write-Error "无法连接到PostgreSQL数据库，请检查连接字符串和PostgreSQL服务状态"
    exit 1
}

Remove-ExistingDatabase
Invoke-DatabaseMigration
Invoke-SeedData

Write-Host "数据库部署完成！" -ForegroundColor Green
Write-Host "连接字符串: $ConnectionString" -ForegroundColor Cyan